package com.china08.yxyapi.service.yxweike.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.entity.db.lessons.YxyLessonsSynchroLessonItem;
import com.china08.yxyapi.entity.db.res.YxyResBookContentsKnoledges;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.repository.db.YxyLessonsSynchroLessonItemRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsKnoledgesRepository;
import com.china08.yxyapi.service.yxweike.YxyResWeikeService;
import com.china08.yxyapi.util.YxyResUtil;

@Service
public class YxyResWeikeServiceImpl implements YxyResWeikeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(YxyResWeikeServiceImpl.class);

    @Autowired
    private ElasticsearchTemplate et;

    @Autowired
    private YxyResUtil yxyResUtil;

    @Autowired
    public YxyLessonsSynchroLessonItemRepository yxyLessonsSynchroLessonItemRepository;

    @Autowired
    private YxyResBookContentsKnoledgesRepository yxyResBookContentsKnoledgesRepository;

    @Override
    public Page<ElasticYxyResResource> findByBookContentAndLessonItemNot(String bookcontent, String lessonId,
            String keyword, Pageable pageable) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 根据章节找知识点
        List<String> list = yxyResUtil.findTocByTocParent(bookcontent);
        List<Integer> knowIds = new ArrayList<Integer>();
        if (CollectionUtils.isNotEmpty(list)) {
            List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                    .findByBookContentIdIn(list);
            knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(knowIds)) {
            knowIds.add(0000);
        }
        BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
        TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
        TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
        TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
        knoBuilder.should(builderknowOne);
        knoBuilder.should(builderknowTwo);
        knoBuilder.should(builderknowThree);
        boolQueryBuilder.must(knoBuilder);
        //
        // 云校微课
        TermQueryBuilder yxBuilder = new TermQueryBuilder("isYxYunRes", 1);
        boolQueryBuilder.must(yxBuilder);
        // 未删除
        TermQueryBuilder notDelBuilder = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(notDelBuilder);
        // 已审核
        TermQueryBuilder statusBuilder = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(statusBuilder);

        if (StringUtils.isNoneBlank(keyword)) {
            MatchQueryBuilder builder = new MatchQueryBuilder("title", keyword);
            boolQueryBuilder.must(builder);
        }
        //
        List<YxyLessonsSynchroLessonItem> items = yxyLessonsSynchroLessonItemRepository
                .findByLessonIdAndStatusNot(lessonId, -1);
        List<String> weikeId = items.stream().map(x -> x.getWeikeId()).collect(Collectors.toList());
        if (weikeId.size() > 0) {
            TermsQueryBuilder builder = new TermsQueryBuilder("id", weikeId);
            boolQueryBuilder.mustNot(builder);
        }
        //
        return getPage(boolQueryBuilder, pageable);
    }

    @Override
    public Page<ElasticYxyResResource> getPage(BoolQueryBuilder boolQueryBuilder, Pageable pageable) {
        SearchQuery query = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(boolQueryBuilder).build();
        LOGGER.info("======================ES====================ES========================");
        LOGGER.info(boolQueryBuilder.toString());
        LOGGER.info("======================ES====================ES========================");
        Page<ElasticYxyResResource> page = et.queryForPage(query, ElasticYxyResResource.class);
        return page;
    }

    @Override
    public List<ElasticYxyResResource> findByIdIn(List<String> ids) {
        Pageable pageable = new PageRequest(0, ids.size());
        TermsQueryBuilder queryBuilder = new TermsQueryBuilder("id", ids);
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(queryBuilder).withPageable(pageable).build();
        return et.queryForList(query, ElasticYxyResResource.class);
    }

}
